define(["angularAMD"], function (angularAMD) {
    angularAMD.service('QT07_SaveQueryService', ['$state','$rootScope', '$filter', '$stateParams', 'config', '$mdDialog', 'MMWService',
        function ($state, $rootScope, $filter, $stateParams, config, $mdDialog, $MMWService) {

            var service = this;

            service.init = function(option, call_back){
                openDialog(option, call_back);
            };

            function openDialog(option, call_back){
                $mdDialog.dialog(
                    'module/moduleQT/program/QT07/dialog/QT07_SaveQueryService.html',
                    function (dialog) {
                        return {
                            css_url:
                                "module/moduleQT/program/QT07/dialog/QT07_SaveQueryService.css",
                            modelName: "",
                            condList: option.conditionList,
                            date: moment().format("YYYY/M/D"),
                            back() {
                                dialog.hide();
                            },
                            async confirm() {
                                const resp = await saveTraceModel(dialog.modelName,dialog.condList);
                                if (resp.Succeed === false && resp.existed === true) {
                                    $rootScope.showAlert($filter("translate")("QT07.errMsg.model_exist"));
                                    return
                                }
                                
                                dialog.hide();
                                call_back && call_back(dialog);
                            },
                        };
                    }
                );
            };

            const service_QTR_Step1 = (content) => {
                return new Promise(async (resolve, reject) => {
                    let result;
                    $MMWService.sendToServer({
                        uri: "ServicesSTD.Module_LEAN.QTR_Step1",
                        content: content,
                        success: (data) => (result = resolve(data)),
                    });

                    return result;
                });
            };

            const saveTraceModel = async (modelName, condList) => {
                const content = {
                    Name: "SaveTraceModel",
                    MODELNAME: modelName,
                    CondList: condList
                };
                const resp = await service_QTR_Step1(content);
                return resp;
            };
        }
    ])
});
